<template>
  <div class="app-container">
    <!-- v-permission="['data:area:read']"
    v-permission="['data:area:create']"
    v-permission="['data:area:update']"
    v-permission="['data:area:delete']" -->
    <!-- 地区资料 -->
    <!-- 查询和其他操作 -->
    <el-form :inline="true" class="demo-form-inline filter">
      <el-form-item label="地区名称">
        <el-input v-model.trim="listQuery.fsiteName" clearable class="filter-item" placeholder="请输入地区名称"/>
      </el-form-item>
      <el-form-item label="上级地区">
        <el-select v-model="listQuery.fsiteParent" clearable filterable class="filter-item" placeholder="请选择上级地区">
          <el-option
            v-for="item in fsiteNoBelongOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="地区类型">
        <el-select v-model="listQuery.fsiteLevel" clearable filterable class="filter-item" placeholder="请选择地区类型">
          <el-option v-for="(key, value) in siteTypeMap" :key="key" :label="key" :value="value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <!--<el-input v-model.trim="listQuery.fsiteLevel" clearable class="filter-item" style="width: 200px;" placeholder="请输入地区类型"/>-->
        <el-button :style="{background:buttonColor.lookup,color:buttonColor.color}" round size="medium" class="filter-item" @click="handleFilter">查找</el-button>
        <el-button :style="{background:buttonColor.add ,color:buttonColor.color}" round size="medium" class="filter-item" @click="handleCreate">添加</el-button>
      </el-form-item>
    </el-form>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :height="buttonColor.clientHeight" :data="list" :header-cell-style="tableColor" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" :width="buttonColor.operationTwo" label="操作" class-name="small-padding">
        <template slot-scope="scope">
          <div class="operationButton">
            <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="handleUpdate(scope.row)">
              <img src="../../../public/images/edit.png" >
              编辑
            </div>
            <div :style="{color:buttonColor.delete,cursor:'pointer'}" @click="handleDelete(scope.row)">
              <img src="../../../public/images/del.png" >
              删除
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column :index="indexMethod" width="108" align="center" label="序" type="index"/>
      <el-table-column width="244" align="left" label="地区编号" prop="fsiteNo"/>
      <el-table-column align="left" label="地区名称" prop="fsiteName"/>
      <el-table-column :formatter="formatSite" align="left" label="上级地区" prop="fsiteParent"/>
      <el-table-column width="108" align="left" label="地区类型" prop="fsiteLevel">
        <template slot-scope="scope">
          <span v-if="scope.row.fsiteLevel==0" :style="{color:buttonColor.provinceColor}">{{ scope.row.fsiteLevel | siteTypeFilter }}</span>
          <span v-else-if="scope.row.fsiteLevel==1" :style="{color:buttonColor.cityColor}">{{ scope.row.fsiteLevel | siteTypeFilter }}</span>
          <span v-else :style="{color:buttonColor.areaColor}">{{ scope.row.fsiteLevel | siteTypeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column width="108" align="left" label="状态" prop="fsiteState">
        <template slot-scope="scope">
          <span v-if="scope.row.fsiteState==0" :style="{color:buttonColor.statedisable}">{{ scope.row.fsiteState | statusFilter }}</span>
          <span v-else :style="{color:buttonColor.statestart}">{{ scope.row.fsiteState | statusFilter }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogFormVisible" width="auto">
      <template slot="title">
        <div :style="titleColor">{{ textMap[dialogStatus] }}</div>
      </template>
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="auto">
        <el-row>
          <el-col :span="12">
            <el-form-item class="required" label="地区编号" prop="fsiteNo">
              <el-input v-model.number="dataForm.fsiteNo" :disabled="dialogStatus=='update'"/><!-- oninput="value=value.replace(/[^\d]/g,'')"-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="el-form-item-small" label="地区类型" prop="fsiteLevel">
              <el-select v-model="dataForm.fsiteLevel" class="filter-item" placeholder="请选择地区类型">
                <el-option v-for="(key, value) in siteTypeMap" :key="key" :label="key" :value="value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item class="required" label="地区名称" prop="fsiteName">
              <el-input v-model="dataForm.fsiteName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上级地区" prop="fsiteParent">
              <el-select v-model="dataForm.fsiteParent" clearable filterable placeholder="请选择">
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item class="required" label="纬度" prop="fsiteL">
              <el-input v-model="dataForm.fsiteL" @focus="clickMap"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="required" label="经度" prop="fsiteD">
              <el-input v-model="dataForm.fsiteD" @focus="clickMap"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item class="el-form-item-small" label="状态" prop="fsiteState">
              <el-select v-model="dataForm.fsiteState" class="filter-item" placeholder="请选择状态">
                <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-show="dataForm.fsiteLevel === '3'" label="学校图片(2M内)" prop="fimage">
              <!--<el-input v-model="dataForm.fimage"/>-->
              <el-upload
                v-model="dataForm.fimage"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="uploadPath"
                :data="formdata2(dataForm.fsiteNo)"
                class="avatar-uploader">
                <img v-if="dataForm.fimage" :src="dataForm.fimage" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <!--<el-form-item label="操作员" prop="foperator">
          <el-input v-model="dataForm.foperator"/>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" round @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" :style="{background:buttonColor.confirm,color:buttonColor.color}" round @click="createData">确定</el-button>
        <el-button v-else :style="{background:buttonColor.confirm,color:buttonColor.color}" round @click="updateData">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogFormVisible2" fullscreen width="1200px" height="800px" style="width: 100%; height: 80%; padding-top:0px;">
      <template slot="title">
        <div :style="titleColor">百度地图</div>
      </template>
      <div slot="title" align="right" style="margin-top:10px; margin-right: 30px">
        <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" round @click="dialogFormVisible2 = false">取消</el-button>
        <el-button :style="{background:buttonColor.confirm,color:buttonColor.color}" round @click="setLatLng">确定</el-button>
      </div>
      <cmap :center="dataForm.fsiteParent" :keyword="dataForm.fsiteName" style="margin-top:0px; width: 100%;" @transfer="getPoint"/>
    </el-dialog>

  </div>
</template>

<script>
import { listArea, createArea, updateArea, deleteArea, fsiteNoBelongOptions } from '@/api/area'
import moment from 'moment'
import Pagination from '@/components/Pagination'
import { uploadPath } from '@/api/eqtOrder'
import cmap from './baiduMap'
import { tableColor, titleColor, buttonColor } from '@/filters/index'

const siteTypeMap = {
  0: '省',
  1: '市',
  2: '区'
}

const statusMap = {
  0: '禁用',
  1: '启用'
}

export default {
  name: 'Area',
  components: { Pagination, cmap },
  filters: {
    siteTypeFilter(type) {
      return siteTypeMap[type]
    },
    statusFilter(type) {
      return statusMap[type]
    }
  },
  data() {
    return {
      uploadPath,
      list: null,
      total: 0,
      fsiteNoBelongOptions: null,
      center: '北京',
      lat: 0,
      lng: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        fsiteName: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      siteTypeMap,
      statusMap,
      dataForm: {
        id: undefined,
        fsiteNo: undefined,
        fimage: undefined,
        fsiteName: undefined,
        fsiteParent: undefined,
        fsiteLevel: undefined,
        fsiteL: undefined,
        fsiteD: undefined,
        fsiteState: undefined,
        fupddate: undefined,
        foperator: undefined
      },
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      tableColor: tableColor,
      titleColor: titleColor,
      buttonColor: buttonColor,
      rules: {
        fsiteNo: [
          { required: true, message: '地区编号不能为空', trigger: 'blur' }
        ],
        fsiteName: [
          { required: true, message: '地区名称不能为空', trigger: 'blur' }
        ],
        fsiteLevel: [
          { required: true, message: '地区类型不能为空', trigger: 'blur' }
        ],
        fsiteL: [
          { required: true, message: '纬度不能为空', trigger: 'blur' }
        ],
        fsiteD: [
          { required: true, message: '经度不能为空', trigger: 'blur' }
        ],
        fsiteState: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ]
      },
      permissionDialogFormVisible: false,
      systemPermissions: null,
      assignedPermissions: null,
      permissionForm: {
        roleId: undefined,
        permIds: []
      }
    }
  },
  created() {
    this.getList()
    fsiteNoBelongOptions(3)
      .then(response => {
        this.fsiteNoBelongOptions = response.data.data.list
      })
      .catch(() => {
        this.fsiteNoBelongOptions = []
      })
  },
  methods: {
    handleAvatarSuccess(res, file) {
      // this.dataForm.fimage = URL.createObjectURL(file.raw)
      this.dataForm.fimage = res.data
      const time = new Date().getTime()
      this.dataForm.fimage = `${this.dataForm.fimage}?time=${time}`
    },
    formdata2: function(fsiteno) {
      // const formdata = new FormData()
      // formdata.append('fpointno', '123456')
      return { 'ftype': '2', 'fsiteno': fsiteno }
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isLt2M // isJPG &&
    },
    formatStatus: function(row, column) {
      return row.fsiteState === 1 ? '启用' : '禁用'
    },
    dateFormat(row, column) {
      const date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    formatSite: function(row, column) {
      if (this.fsiteNoBelongOptions) {
        for (let i = 0; i < this.fsiteNoBelongOptions.length; i++) {
          if (row.fsiteParent === this.fsiteNoBelongOptions[i].value) {
            return this.fsiteNoBelongOptions[i].label
          }
        }
        return ''
      } else {
        return ''
      }
    },
    getList() {
      this.listLoading = true
      listArea(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        fsiteNo: undefined,
        fimage: undefined,
        fsiteName: undefined,
        fsiteParent: undefined,
        fsiteLevel: undefined,
        fsiteL: undefined,
        fsiteD: undefined,
        fsiteState: undefined,
        fupddate: undefined,
        foperator: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.dataForm.fsiteState = '1'
      this.dataForm.fsiteLevel = '0'
      if (this.fsiteNoBelongOptions.length > 0) {
        this.dataForm.fsiteParent = this.fsiteNoBelongOptions[0].value
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    clickMap() {
      // this.resetForm()
      this.dialogFormVisible2 = true
      this.lat = 0
      this.lng = 0
      // this.dataForm.fsiteState = '1'
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    getPoint(point) {
      this.lat = point.lat
      this.lng = point.lng
    },
    setLatLng() {
      this.dialogFormVisible2 = false
      this.dataForm.fsiteL = this.lat
      this.dataForm.fsiteD = this.lng
      this.$refs['dataForm'].validateField('fsiteL')
      this.$refs['dataForm'].validateField('fsiteD')
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id
          this.dataForm.fupddate = new Date()
          createArea(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加地区成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.msg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dataForm.fsiteLevel = row.fsiteLevel.toString()
      this.dataForm.fsiteState = row.fsiteState.toString()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id
          this.dataForm.fupddate = new Date()
          updateArea(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.fsiteNo === this.dataForm.fsiteNo) {
                  const index = this.list.indexOf(v)
                  this.dataForm.fsiteState = parseInt(this.dataForm.fsiteState)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新地区资料成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.msg
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否要删除该地区资料', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteArea(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除地区资料成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.data
            })
          })
      })
    },
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
     /*处理input type = number的上下箭头*/
   input::-webkit-outer-spin-button,
   input::-webkit-inner-spin-button {
     -webkit-appearance: none;
   }
  input[type="number"]{
    -moz-appearance: textfield;
  }
</style>
